<template>
  <div class="app-container">
    <div class="block" style="width:100% !important">
      <div class="" model="queryParams" style="width:100% !important">
        <el-input v-model="queryParams.supplierCode" style="width: 120px" placeholder="Supplier Code" clearable />
        &nbsp;&nbsp;
        &nbsp;&nbsp;
        <el-input v-model="queryParams.fullName" style="width: 160px" placeholder="Full Name" clearable />
        &nbsp;&nbsp;
        &nbsp;&nbsp;
        <el-button type="primary" @click="search">{{
          $t("ship.button.search")
        }}</el-button>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span> 

        <el-button type="primary" @click="addClickEvent"  v-hasPermi="['bunkerOrderAgency:edit']">
          {{ $t("ship.button.plus") }}
        </el-button>

      </div>
    </div>
	
  </div>

  <el-table stripe class="daf-table" :data="listData" style="width: 100%" @sort-change="handleSortChange">
    <el-table-column prop="agencyCode" label="Agency Code" />
    <el-table-column prop="fullName" label="Full Name"  />
    <!-- <el-table-column prop="clientType" label="Client Type" sortable /> -->
    <el-table-column prop="contact" label="Contact" />
    <el-table-column prop="mobile" label="mobile" />
 
 
   <el-table-column prop="status" label="Status" width="150">
      <template #default="scope"> 
        <el-select
              v-model="scope.row.status"
              class="ipt"
              clearable 
              :disabled="scope.row.status == 1 || scope.row.satus == 2"
              @change="handleStatus(scope.row)"
            >
              <el-option :key="index" :label="item" :value="index" v-for="(item,index) in  statuss"  />
        </el-select>
      </template>  
    </el-table-column>  
 
    <el-table-column prop="createBy" label="Create By"  />
    <el-table-column label="Operation" width="200"  v-hasPermi="['bunkerOrderAgency:edit']">
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
        }}</span>&nbsp;&nbsp;
        <span class="btn-primary" :disabled="scope.row.status == 1" @click="removeClickEvent(scope.row.id)">{{
          $t("ship.button.remove")
        }}</span>  
      </template>
    </el-table-column>
  </el-table>

  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="500" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible"  >
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="24">
          <el-form-item label="Agency Code" label-width="120px" prop="agencyCode" required>
            <el-input v-model="formParam.agencyCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Full Name" label-width="120px" prop="fullName" required>
            <el-input v-model="formParam.fullName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Contact" label-width="120px" prop="contact" required>
            <el-input v-model="formParam.contact"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Mobile" label-width="120px" prop="mobile" required>
            <el-input v-model="formParam.mobile"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Email" label-width="120px" prop="email" >
            <el-input v-model="formParam.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
        }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>

      </span>
    </template>
  </el-dialog> 
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import service from "@/utils/request";
import type {  UploadUserFile } from "element-plus"; 
const uploadUrl='/shipping/client/upload'
const router = useRouter();
const custForm = ref(null);
const addFormModal = ref();
const dialogTitle = ref("");
const initForm = {
  id: null,
  title: null, 
  fullName: null,
  agencyCode: null,
  contact: null,
  mobile: null,
  email: null,
};
const formParam = reactive(Object.assign({}, initForm)); 
const total = ref(0);
const statuss = ['UnApprove', "Approve", "Reject"]
const mailValid = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("email can't be blank"));
  } else if (!/^(?:\w+\.?)*\w+@(?:\w+\.)*\w+$/.test(value)) {
    callback(new Error('The email format is illegal!'));
  } else {
    callback();
  }
}
const rules = ref({
  email: [{ required: true, trigger: "blur", validator: mailValid }]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  agencyCode: null,
  fullName: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/agency/getTable", { params: queryParams });
  listData.value = result.data;
  total.value = result.total;
};
const handleStatusChange =async(row) => {
      let text = row.status === 1 ? "approve" : "reject";
      ElMessageBox.confirm('Cconfirm to "' + text + '""' + row.fullName + '"?')
        .then( () => {
            service.put("shipping/agency", row);
        })
        .then(() => {
          // @ts-ignore
          ElNotification.success(text + " success");
        })
        .catch(()=> {
          row.status = row.status === "0" ? "1" : "0";
        });
    }
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => { 
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  dialogFormVisible.value = true
  dialogTitle.value = "update Agency"
  isAdd = false
  //addFormModal.value.show(row);
};

const handleStatus=(row:any)=>{
    if(row.status != null && row.status != 0){
      ElMessageBox.confirm("Confirm to update the agency Status？", "Confirmation Information", {
          type: "warning",
          confirmButtonText: "Confirm",
          cancelButtonText: "Cancel",
        }).then(async () => { 
          await service.put(`shipping/agency`, row);
          ElNotification.success({
            title: "Prompt information",
            message: "update booking status success!",
            position: "bottom-right"
          });
          
        });
    }
}


const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to delete the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/agency/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};
 

let isAdd = false;
const loading = ref(false);
const photos = ref<UploadUserFile[]>([]);
const addClickEvent = () => { 
  dialogFormVisible.value = true
  dialogTitle.value = "Add Agency"
  isAdd = true
  //addFormModal.value.show();
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await service[isAdd ? "post" : "put"]("shipping/agency", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    refreshTable();
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
}; 

const uploadFile = async (event) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/country/uploadFile", formData);
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};



const submitUploadForm = async (data) => {
  console.log(data,'data');
  
  // @ts-ignore
  const params = {
    clientId: data.id,
    photos: data.photos  };

  await service["put"]("/shipping/client/updatePhotos", params);
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};
onMounted(async () => {
  refreshTable();
});
</script>
<style>
.el-table__expand-column .cell {
  display: none;
}

.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}
</style>
